/*
Copyright (c) 2008, Oleg S. Estekhin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of the copyright holders nor the names of its
      contributors may be used to endorse or promote products derived from this
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package ebml.viewer;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import ebml.ElementDescriptor;
import ebml.ElementDescriptorProvider;
import ebml.VInteger;
import ebml.io.EbmlReader;
import ebml.io.FileInputSource;
import ebml.io.InputSource;

/** Parses an EBML file. */
public final class FileTask implements Runnable {

    private final List<FileTaskListener> listeners;

    private final File file;

    private final ElementDescriptorProvider descriptorProvider;

    private InputSource source;

    private EbmlReader reader;


    /**
     * Creates a new <code>FileTask</code> object.
     *
     * @param file the file
     * @param descriptorProvider the descriptor provider
     *
     * @throws NullPointerException if <code>file</code> or <code>descriptorProvider</code> is <code>null</code>
     */
    public FileTask(File file, ElementDescriptorProvider descriptorProvider) {
        if (file == null) {
            throw new NullPointerException("file is null");
        }
        if (descriptorProvider == null) {
            throw new NullPointerException("descriptorProvider is null");
        }
        listeners = new CopyOnWriteArrayList<FileTaskListener>();
        this.file = file;
        this.descriptorProvider = descriptorProvider;
    }


    /**
     * Returns the file.
     *
     * @return the file
     */
    public File getFile() {
        return file;
    }


    @Override
    public void run() {
        fireStartFile(file);
        reader = null;
        try {
            source = new FileInputSource(file);
            reader = new EbmlReader(source, file.length());
            parseContainer();
        } catch (IOException e) {
            fireError(e);
        } catch (InterruptedException e) {
            fireError(e);
        } catch (OutOfMemoryError e) {
            fireFatalError(e);
            throw e;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignored) {
                }
            }
            try {
                fireEndFile();
            } catch (Throwable ignored) {
            }
        }
    }

    private void parseContainer() throws IOException, InterruptedException {
        while (reader.hasNext()) {
            long position = source.getPosition();
            VInteger identifier = reader.getIdentifier();
            VInteger size = reader.getSize();
            ElementDescriptor descriptor = descriptorProvider.getElementDescriptor(identifier);
            if (descriptor == null) {
                fireUnknownElement(position, identifier, size);
            } else {
                switch (descriptor.getType()) {
                    case SIGNED_INTEGER:
                        fireSignedIntegerElement(position, descriptor, size, reader.readSignedInteger());
                        break;
                    case UNSIGNED_INTEGER:
                        fireUnsignedIntegerElement(position, descriptor, size, reader.readUnsignedInteger());
                        break;
                    case FLOAT:
                        fireFloatElement(position, descriptor, size, reader.readFloat());
                        break;
                    case ASCII_STRING:
                        fireAsciiStringElement(position, descriptor, size, reader.readString());
                        break;
                    case UTF_8_STRING:
                        fireUnicodeStringElement(position, descriptor, size, reader.readUTF());
                        break;
                    case DATE:
                        fireDateElement(position, descriptor, size, reader.readDate());
                        break;
                    case BINARY:
                        fireBinaryElement(position, descriptor, size);
                        break;
                    case CONTAINER:
                        fireStartContainer(position, descriptor, size);
                        reader.enterContainer();
                        parseContainer();
                        reader.leaveContainer();
                        fireEndContainer(source.getPosition(), descriptor);
                        break;
                    default:
                        throw new AssertionError(descriptor.getType());
                }
            }
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }
        }
    }


    public void addFractalModelListener(FileTaskListener listener) {
        listeners.add(listener);
    }

    public void removeFractalModelListener(FileTaskListener listener) {
        listeners.remove(listener);
    }


    private void fireStartFile(File file) {
        long size = file.isFile() ? file.length() : 0;
        for (FileTaskListener listener : listeners) {
            listener.startFile(file, size);
        }
    }

    private void fireSignedIntegerElement(long position, ElementDescriptor descriptor, VInteger size, long value) {
        for (FileTaskListener listener : listeners) {
            listener.signedIntegerElement(position, descriptor, size, value);
        }
    }

    private void fireUnsignedIntegerElement(long position, ElementDescriptor descriptor, VInteger size, long value) {
        for (FileTaskListener listener : listeners) {
            listener.unsignedIntegerElement(position, descriptor, size, value);
        }
    }

    private void fireFloatElement(long position, ElementDescriptor descriptor, VInteger size, Number value) {
        for (FileTaskListener listener : listeners) {
            listener.floatElement(position, descriptor, size, value);
        }
    }

    private void fireAsciiStringElement(long position, ElementDescriptor descriptor, VInteger size, String value) {
        for (FileTaskListener listener : listeners) {
            listener.asciiStringElement(position, descriptor, size, value);
        }
    }

    private void fireUnicodeStringElement(long position, ElementDescriptor descriptor, VInteger size, String value) {
        for (FileTaskListener listener : listeners) {
            listener.unicodeStringElement(position, descriptor, size, value);
        }
    }

    private void fireDateElement(long position, ElementDescriptor descriptor, VInteger size, long value) {
        for (FileTaskListener listener : listeners) {
            listener.dateElement(position, descriptor, size, value);
        }
    }

    private void fireBinaryElement(long position, ElementDescriptor descriptor, VInteger size) {
        for (FileTaskListener listener : listeners) {
            listener.binaryElement(position, descriptor, size);
        }
    }

    private void fireStartContainer(long position, ElementDescriptor descriptor, VInteger size) {
        for (FileTaskListener listener : listeners) {
            listener.startContainer(position, descriptor, size);
        }
    }

    private void fireEndContainer(long position, ElementDescriptor descriptor) {
        for (FileTaskListener listener : listeners) {
            listener.endContainer(position, descriptor);
        }
    }

    private void fireUnknownElement(long position, VInteger identifier, VInteger size) {
        for (FileTaskListener listener : listeners) {
            listener.unknownElement(position, identifier, size);
        }
    }

    private void fireEndFile() {
        for (FileTaskListener listener : listeners) {
            listener.endFile();
        }
    }

    private void fireError(Throwable e) {
        for (FileTaskListener listener : listeners) {
            listener.error(e);
        }
    }

    private void fireFatalError(Throwable e) {
        for (FileTaskListener listener : listeners) {
            listener.fatalError(e);
        }
    }

}
